<template>
  <div class="order-list">
    <table>
      <thead>
      <tr>
        <th>订单号</th>
        <th>订单人</th>
        <th>地址</th>
        <th>电话</th>
        <th>下单时间</th>
        <th>预计送达时间</th>
        <th>总价</th>
        <th>支付状态</th>
        <th>订单状态</th>
        <th>详细订单</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="indent in currentIndents" :key="indent.indentid">
        <td>{{ indent.indentid }}</td>
        <td>{{ indent.name }}</td>
        <td>{{ indent.address }}</td>
        <td>{{ indent.phone }}</td>
        <td>{{ indent.orderdate }}</td>
        <td>{{indent.gettime }}</td>
        <td>{{ indent.totalprice }}</td>
        <td>{{ indent.paystatus }}</td>
        <td>{{ indent.signstatus }}</td>
        <td><button @click="viewDetail(indent.indentid)">详情</button></td>
        <td>
          <!-- 根据 signstatus 和 paystatus 显示不同的操作按钮 -->
          <button v-if="indent.paystatus === '已支付' && indent.signstatus === '待接单'" @click="acceptOrder(indent.indentid)">接单</button>
          <button v-if="indent.signstatus === '已接单'" @click="deliverOrder(indent.indentid)">配送</button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>

  <!-- 订单明细模态框 -->
  <div v-if="showModal">
    <div class="modal">
      <div class="modal-content">
        <span class="close" @click="closeModal">&times;</span>
        <h2>订单明细</h2>
        <table>
          <tr>
            <th>菜品名称</th>
            <th>价格</th>
            <th>数量</th>
          </tr>
          <tr v-for="detail in modalDetails" :key="detail.id">
            <td>{{ detail.dname }}</td>
            <td>{{ detail.price }}</td>
            <td>{{ detail.count }}</td>
          </tr>
        </table>
      </div>
    </div>
  </div>
  <!-- 分页控件 -->
  <div class="pagination">
    <button @click="goToPage(currentPage - 1)" :disabled="currentPage <= 1">上一页</button>
    <!-- 页码按钮 -->
    <button
        v-for="page in totalPage"
        :key="page"
        :class="{ active: page === currentPage }"
        @click="goToPage(page)"
    >
      {{ page }}
    </button>
    <button @click="goToPage(currentPage + 1)" :disabled="currentPage >= totalPage">下一页</button>
  </div>
</template>

<script setup>
import axios from 'axios';
import {ref, onMounted, computed} from 'vue';

const indents = ref([]);
const showModal = ref(false);
const modalDetails = ref([]);

// 定义一个方法来过滤支付状态为 '已支付' 的订单
function filterIndents(indents) {
  return indents.filter(indent => indent.paystatus === '已支付');
}

// 从 sessionStorage 获取 loginUser 和 selectedAddress 的信息
const loginUser = sessionStorage.getItem('loginUser')
    ? JSON.parse(sessionStorage.getItem('loginUser'))
    : null;
const selectedAddress = sessionStorage.getItem('selectedAddress')
    ? JSON.parse(sessionStorage.getItem('selectedAddress'))
    : null;

// 假设你有一个方法来获取当前登录用户的 mid
const getCurrentMid = () => loginUser ? loginUser.mid : null;

async function fetchIndents() {
  const currentUserMid = getCurrentMid(); // 获取当前用户的 mid

  try {
    const response = await axios.get('http://localhost:8085/indent/getAll');
    // 只映射那些 mallid 与当前用户 mid 一致的订单
    indents.value = response.data
        .filter(indent => indent.mallid === currentUserMid)
        .map(indent => ({
          ...indent,
          addressInfo: selectedAddress ? selectedAddress : null, // 假设所有订单使用相同的地址信息
        }));
  } catch (error) {
    console.error('Error fetching indents:', error);
  }
}

function viewDetail(indentId) {
  axios.get(`http://localhost:8085/indentdetail/listByIndentId/${indentId}`)
      .then(response => {
        console.log('订单明细数据:', response.data);
        modalDetails.value = response.data;
        showModal.value = true;
      })
      .catch(error => {
        console.error('获取订单明细失败:', error);
      });
}

function closeModal() {
  showModal.value = false;
  modalDetails.value = [];
}

function acceptOrder(indentId) {
  const newStatus = '已接单';
  axios.put(`http://localhost:8085/indent/updatesign`, { indentid: indentId, signstatus: newStatus })
      .then(response => {
        if (response.data.errorCode == 200) {
          console.log('订单状态更新成功');
          // 更新本地状态
          indents.value = indents.value.map(indent => {
            if (indent.indentid === indentId) {
              return { ...indent, signstatus: newStatus };
            }
            return indent;
          });
        } else {
          console.error('订单状态更新失败');
        }
      })
      .catch(error => {
        console.error('订单状态更新失败:', error);
      });
}

function deliverOrder(indentId) {
  const newStatus = '已配送';
  axios.put(`http://localhost:8085/indent/updatesign`, { indentid: indentId, signstatus: newStatus })
      .then(response => {
        console.log(response)
        if (response.data.errorCode == 200) {
          console.log('订单状态更新成功');
          // 更新本地状态
          indents.value = indents.value.map(indent => {
            if (indent.indentid === indentId) {
              return { ...indent, signstatus: newStatus };
            }
            return indent;
          });
        } else {
          console.error('订单状态更新失败');
        }
      })
      .catch(error => {
        console.error('订单状态更新失败:', error);
      });
}
// 分页状态
const currentPage = ref(1);
const pageSize = ref(15); // 每页显示的订单数

// 计算总页数
const totalPage = computed(() => {
  return Math.ceil(indents.value.length / pageSize.value);
});

// 当前页的订单
const currentIndents = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return indents.value.slice(start, end);
});

// 分页导航方法
function goToPage(pageNumber) {
  if (pageNumber > 0 && pageNumber <= totalPage.value) {
    currentPage.value = pageNumber;
  }
}
onMounted(() => {
  fetchIndents();
});
</script>

<style scoped>
/* 你的样式 */
.order-list table {
  width: 100%;
  border-collapse: collapse;
}
.order-list th, .order-list td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}
.order-list th {
  background-color: #f2f2f2;
}
.modal {
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 400px;
  top: 200px;
  width: 40%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0); /* Black w/ opacity */
}
.modal-content {
  background-color: #fefefe;
  margin: 15% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 80%; /* Could be more or less, depending on screen size */
}
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
/* 添加分页控件的样式 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.pagination button {
  cursor: pointer;
  padding: 5px 10px;
  margin: 0 5px;
  border: 1px solid #ccc;
  background-color: #f8f8f8;
}
.pagination button.active {
  background-color: #ccc;
}
.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>